package com.atguitu.campus.renwendemo.config;


import com.atguitu.campus.renwendemo.utils.AjaxResult;
import com.atguitu.campus.renwendemo.utils.MyException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;
import java.io.IOException;


@Slf4j
@Controller
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 所有异常捕获
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(value = IOException.class)
    @ResponseBody
    public AjaxResult defaultIOException(HttpServletRequest req, IOException e) throws Exception {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }



    /**
     * 自定义异常捕获
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public AjaxResult jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        log.error(e.getMessage(), e);
        return  AjaxResult.error(e.getMessage());
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("{}",e);
        return AjaxResult.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 权限管理
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public AjaxResult handleAuthorizationExceptionException(AccessDeniedException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(401,"权限不足，无法访问该资源");
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public AjaxResult handleAuthenticationException(AuthenticationException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(403,"权限不足，无法访问该资源");
    }

    @ExceptionHandler(BadCredentialsException.class)
    @ResponseBody
    public AjaxResult handleBadCredentialsException(BadCredentialsException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(401,"认证失败，用户名或密码错误！");
    }


}
